package com.yedean.factory;

import cn.hutool.core.util.StrUtil;
import com.yedean.factory.config.BeanDefinition;
import com.yedean.factory.config.BeanFactoryPostProcessor;
import com.yedean.factory.io.DefaultResourceLoader;
import com.yedean.factory.io.Resource;
import com.yedean.factory.property.PropertyValue;
import com.yedean.factory.property.PropertyValues;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class PropertyPlaceHolderConfiguer implements BeanFactoryPostProcessor {
        
    private static final String DEFAULT_PLACEHOLDER_PREFIX="${";
    
    private static final String DEFAULT_PLACEHOLDER_SUFFIX="}";
    
    private String location;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
        //加载属性文件
        try {
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            InputStream inputStream = resource.getInputStream();
            Properties properties = new Properties();
            properties.load(inputStream);

            String[] definitionNames = factory.getBeanDefinitionNames();
            for (String definitionName : definitionNames) {
                BeanDefinition beanDefinition = factory.getBeanDefinition(definitionName);
                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getPropertyValue()) {
                    Object value = propertyValue.getValue();
                    if (!(value instanceof String)){
                        continue;
                    }
                    String strVal=(String) value;
                    StringBuilder builder = new StringBuilder(strVal);
                    int startIdx=builder.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
                    int stopIdx=builder.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    if (startIdx!=-1&& stopIdx!=-1 &&startIdx<stopIdx){
                        String propKey = strVal.substring(startIdx + 2, stopIdx);
                        String propValue=properties.getProperty(propKey);
                        builder.replace(startIdx,stopIdx+1,propValue);
                        propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(),builder.toString()));
                    }
                }
            }

        }catch (Exception e){
            throw new BeansException("could not load properties!",e);
        }
       
    }
}
